package com.bz.xtcx.manager.controller;

import com.bz.xtcx.manager.comom.XtcxException;
import com.bz.xtcx.manager.entity.CmsCategory;
import com.bz.xtcx.manager.entity.CmsContent;
import com.bz.xtcx.manager.entity.CmsFile;
import com.bz.xtcx.manager.service.ICmsCategoryService;
import com.bz.xtcx.manager.service.ICmsFileService;
import com.bz.xtcx.manager.utils.MyFileUtil;
import com.bz.xtcx.manager.utils.WzStrUtil;
import com.bz.xtcx.manager.vo.VoQueryCms;
import com.bz.xtcx.manager.vo.VoResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("category")
public class CategoryController {
    
    @Autowired
    private ICmsCategoryService cmsCategoryService;
    
    @Autowired
    private ICmsFileService cmsFileService;
    
    @Value("${file.tomcatPath}")
    private String tomcatPath;

    @PostMapping("tree")
    public Object get(@RequestBody VoQueryCms query) {
        VoResponse voRes = new VoResponse();
        voRes.setData(cmsCategoryService.getTreeByCondition(query));
        return voRes;
    }
    
    @GetMapping
    public Object getCategory(@RequestParam("id") String id) {
        VoResponse voRes = new VoResponse();
        voRes.setData(cmsCategoryService.getCategoryById(id));
        return voRes;
    }
    
    /**
     * 获取所有栏目的叶子节点
     * @return
     */
    @GetMapping("getLeafNodes")
    public Object getSubCategory() {
        VoResponse voRes = new VoResponse();
        voRes.setData(cmsCategoryService.getSubCategorys());
        return voRes;
    }
    
    private VoResponse validate(CmsCategory e) {
        VoResponse voRes = new VoResponse();
        if(StringUtils.isEmpty(e.getName())) {
            voRes.setFail(voRes);
            voRes.setMessage("名称不能为空");
            return voRes;
        }
        if(StringUtils.isEmpty(e.getCode())) {
            voRes.setFail(voRes);
            voRes.setMessage("编码不能为空");
            return voRes;
        }
        return voRes;
    }

    @PostMapping
    public Object add(@RequestBody CmsCategory e) {
        VoResponse voRes = validate(e);
        if(voRes.getSuccess()) {
            voRes = cmsCategoryService.add(e);
        }
        return voRes;
    }
    
    @PutMapping
    public Object update(@RequestBody CmsCategory e) {
        VoResponse voRes = validate(e);
        if(voRes.getSuccess()) {
            voRes = cmsCategoryService.update(e);
        }
        return voRes;
    }
    
    @DeleteMapping
    public Object del(@RequestParam("id") String id) {
        VoResponse voRes = new VoResponse();
        if(!cmsCategoryService.del(id)) {
            voRes.setFail(voRes);
        }
        return voRes;
    }
    
    @PutMapping("on")
    public Object On(@RequestParam("id") String id){
        VoResponse voRes = new VoResponse();
        if(!cmsCategoryService.onOrOffCategory(id, 1)) {
            voRes.setFail(voRes);
        }
        return voRes;
    }
    
    @PutMapping("off")
    public Object Off(@RequestBody List<String> ids){
        VoResponse voRes = new VoResponse();
        int count = 1;
        for(String id : ids) {
            if(!cmsCategoryService.onOrOffCategory(id, 0)) {
                voRes.setFail(voRes);
                voRes.setMessage("第" + count + "条数据下架异常；");
                return voRes;
            }
            count ++;
        }
        return voRes;
    }
    
    private VoResponse validateContent(CmsContent e) {
        VoResponse voRes = new VoResponse();
        if(StringUtils.isEmpty(e.getTitle())) {
            voRes.setFail(voRes);
            voRes.setMessage("标题不能为空");
            return voRes;
        }
        if(StringUtils.isEmpty(e.getCategroyId())) {
            voRes.setFail(voRes);
            voRes.setMessage("所属栏目不能为空");
            return voRes;
        }
        if(e.getTypeId() == null || e.getTypeId() < 1 || e.getTypeId() > 2) {
            voRes.setFail(voRes);
            voRes.setMessage("内容类型错误");
            return voRes;
        }
        if(e.getCheckStatus() == null || e.getCheckStatus() < -1 || e.getCheckStatus() > 1) {
            voRes.setFail(voRes);
            voRes.setMessage("内容状态错误");
            return voRes;
        }
        return voRes;
    }
    
    /**
     * 草稿，提交待审核内容
     * @param e
     * @return
     */
    @PostMapping("content/submit")
    public Object submitContent(@RequestBody CmsContent e) {
        VoResponse voRes = validateContent(e);
        if(voRes.getSuccess()) {
            if(e.getCheckStatus() == 1) {
                e.setCheckStatus(0);
            }
            voRes = cmsCategoryService.addOrUpdate(e);
        }
        return voRes;
    }
    
    /**
     * 草稿，提交，直接发布内容
     * @param e
     * @return
     */
    @PostMapping("content/add")
    public Object addContent(@RequestBody CmsContent e) {
        VoResponse voRes = validateContent(e);
        if(voRes.getSuccess()) {
            voRes = cmsCategoryService.addOrUpdate(e);
        }
        return voRes;
    }
    
    @DeleteMapping("content")
    public Object delContent(@RequestParam("id") String id) {
        VoResponse voRes = new VoResponse();
        if(!cmsCategoryService.delContent(id)) {
            voRes.setFail(voRes);
        }
        return voRes;
    }
    
    @PostMapping("content/page")
    public Object getAllContent(@RequestBody VoQueryCms query, @RequestParam("pageNum") int pageNum, @RequestParam("pageSize") int pageSize,
            @RequestParam(value="orderBy",required=false)  String orderBy) {
        VoResponse voRes = new VoResponse();
        try {
            voRes.setData(cmsCategoryService.getPageByCondition(query, pageNum, pageSize, orderBy));
        } catch (XtcxException e) {
            voRes.setFail(voRes);
            voRes.setMessage("查询内容错误:" + e.getMessage());
        } catch (Exception e) {
            voRes.setFail(voRes);
            voRes.setMessage("查询内容时发生系统错误:" + e.getMessage());
        }
        return voRes;
    }
    
    @GetMapping("content")
    public Object getContent(@RequestParam("id") String id) {
        VoResponse voRes = new VoResponse();
        voRes.setData(cmsCategoryService.getContentById(id));
        return voRes;
    }
    
    @PutMapping("content/reject")
    public Object contentReject(@RequestBody Map<String,String> map){
        VoResponse voRes = cmsCategoryService.reject(map.get("id"), map.get("info"));
        return voRes;
    }
    
    /**
     * 审核 批量
     * @param ids
     * @return
     */
    @PutMapping("content/check")
    public Object contentCheck(@RequestBody List<String> ids){
        VoResponse voRes = cmsCategoryService.check(ids);
        return voRes;
    }
    
    @PutMapping("content/on")
    public Object contentOn(@RequestBody List<String> ids){
        //VoResponse voRes = cmsCategoryService.onOrOff(id, 1);
        VoResponse voRes = null;
        for(String id : ids) {
            voRes = cmsCategoryService.onOrOff(id, 1);
            
        }
        return voRes;
    }
    
    @PutMapping("content/off")
    public Object contentOff(@RequestBody List<String> ids){
        VoResponse voRes = null;
        for(String id : ids) {
            voRes = cmsCategoryService.onOrOff(id, 0);
            
        }
        return voRes;
    }
    
    @PutMapping("content/top")
    public Object contentTop(@RequestParam("id") String id, @RequestParam(value = "order", required=false, defaultValue="0") Integer order){
        VoResponse voRes = cmsCategoryService.isTop(id, order);
        return voRes;
    }
    
    /**
     * 获取活动和内容我的代办，待审和驳回数量
     * @return
     */
    @GetMapping("getMyTaskSum")
    public Object getMyTaskSum(){
        return cmsCategoryService.myTaskDoingSum();
    }
    
    /**
     * 附件上传form
     * @param file
     * @param fileType
     * @return
     */
    @PostMapping("content/upload")
    public Object upload(@RequestParam("file")MultipartFile file, @RequestParam(value="fileType",defaultValue="0") String fileType) {
        MyFileUtil util = new MyFileUtil();
        String path = "/content/";
        String filePath = tomcatPath + path;
        VoResponse voRes = null;
        CmsFile e = null;
        String fileName = file.getOriginalFilename();
        if(fileType.equals("0")) {
            String [] suffixNames = {".jpg", ".jpeg", ".png", ".gif", ".xls", ".xlsx", ".doc", ".docx", ".ppt", ".pptx", ".txt"};
            voRes = util.upload(file, filePath, suffixNames);
            if(voRes.getSuccess()) {
                e = new CmsFile();
                e.setFileName(fileName);
                e.setOwnerType(0);
                e.setReqRelUrl(voRes.getData().toString());
                String sp = path + voRes.getData();
                if (WzStrUtil.isNotBlank(sp) && sp.startsWith("/")) {
                    sp = sp.substring(1);
                }
                e.setSavePath(sp);
                if(cmsFileService.add(e)) {
                    voRes.setData(e); 
                }
            }
        }else {
            String [] suffixNames = {".jpg", ".jpeg", ".png", ".gif"};
            voRes = util.upload(file, filePath, suffixNames);
            if(voRes.getSuccess()) {
                e = new CmsFile();
                e.setFileName(fileName);
                e.setOwnerType(0);
                e.setReqRelUrl(voRes.getData().toString());
                String sp = path + voRes.getData();
                if (WzStrUtil.isNotBlank(sp) && sp.startsWith("/")) {
                    sp = sp.substring(1);
                }
                e.setSavePath(sp);
                voRes.setData(e);
            }
        }
        
        return voRes;
    }
    
    /**
     * 文件上传base64
     * @param strfile
     * @return
     */
    @PostMapping("content/upload2")
    public Object upload2(@RequestBody String strfile) {
        MyFileUtil util = new MyFileUtil();
        String type = "/content/";
        String [] suffixNames = {".jpg", ".jpeg", ".png", ".gif", ".xls", ".xlsx", ".doc", ".docx", ".ppt", ".pptx", ".txt"};
        VoResponse voRes = util.upload2(strfile, type, suffixNames);
        return voRes;
    }
    
    @GetMapping("content/download")
    public Object downloadFile(HttpServletResponse response, @RequestParam("fileName") String fileName) {
        MyFileUtil util = new MyFileUtil();
        String type = "/content/";
        VoResponse voRes = util.download(fileName, type, response);
        return voRes;
    }
    
}
